<?php
/**
 * Created by PhpStorm.
 * User: fengyan
 * Date: 17-11-13
 * Time: 上午9:37
 */

namespace App\Repositories\Basic;

use App\Exceptions\MyException;
use App\Models;
class AdvRepository extends BasicRepository
{
    protected $advDataModel;
    public function __construct()
    {
        parent::__construct();
        $this->model = new Models\Basic\Adv();
        $this->advDataModel = new Models\Basic\AdvData();
    }

    private static $instance;

    /**
     * 实现单例
     */
    public static function getInstance()
    {
        if (!(self::$instance instanceof self)) {
            self::$instance = new self();
        }

        return self::$instance;
    }


    /**
     * 声明实例模型
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getSelectModel(array $filter = []): \Illuminate\Database\Eloquent\Builder
    {
        // TODO: Implement getSelectModel() method.
    }

    public function getModel()
    {
        return $this->model;
    }

    /**
     * 广告位分页列表
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getAdvPaginateData()
    {
        $model = $this->model;
        $model = $this->getSiteIdModel($model, []);

        return $model->orderBy('created_at', 'desc')->paginate($this->pageSize);
    }

    /**
     * 广告数据分页列表
     * @param int $advId
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getAdvDataPaginateData($advId = 0)
    {
        $model = $this->advDataModel;
        $model = $this->getSiteIdModel($model, []);

        return $model->where('adv_id', '=', $advId)->orderBy('sort', 'asc')->orderBy('created_at', 'desc')->paginate($this->pageSize);
    }

    /**
     * 获取广告数据单条详情
     * @param $advDataId
     * @return mixed
     */
    public function getAdvDataDetailById($advDataId)
    {
        return $this->advDataModel->where($this->getPrimaryKey(), '=', $advDataId)->first();
    }

    /**
     * 保存广告数据
     * @param array $info
     * @param string $action
     * @return mixed
     * @throws MyException
     */
    public function saveData(array $info, $action = '')
    {
        if (!method_exists($this, $action)) {
            throw (new MyException("不存在该方法", -1));
        }

        return $this->$action($info, $this->advDataModel);
    }

    /**
     * @param $name
     * @return mixed
     */
    public function getAdvDataListByName($name)
    {
        return $this->model->where('name', '=', $name)->first();
    }
}